package com.tron.dobest.webfilter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class TronOncePerRequestFilter extends OncePerRequestFilter implements ApplicationContextAware, BeanFactoryAware {

    private ApplicationContext applicationContext;

    private BeanFactory beanFactory;


    /**
     * 先进该方法读取配置文件，判断时候拦截
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        //不拦截的地址：读取配置文件，或者从数据源获取
        List<String> ignoreURL = Arrays.asList("webjars","swagger-resources","api-docs","doc.html","login","logout","favicon.ico");
        String requestURI = request.getRequestURI();
        boolean isIgnore = false;
        for (String s : ignoreURL) {
            if (requestURI.toLowerCase().contains(s)) {
                isIgnore = true;
                break;
            }
        }
        //不过滤的地址返回true
        return isIgnore;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("======TronOncePerRequestFilter======拦截请求路径url:{}",request.getRequestURL());
        //这里添加验证逻辑
        String header = request.getHeader("Authorization");
        log.info("======Authorization信息：======{}", header);
        request.setAttribute("presentUserId","0001");
//        if (header == null) {
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("text/html;charset=utf-8");
//            String msg = "Authorization信息获取失败";
//            response.getWriter().write("{\"msg\":" + msg + ",\"code\":400}");
//        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
